import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';
import 'package:flutterdemo/dart/demo.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Welcome to Flutter',
      //主题
      theme: new ThemeData(
        primaryColor: Colors.blue,
      ),
      //应用首页路由
      home: new RandomWords(),
    );
  }
}

class RandomWords extends StatefulWidget {
  @override
  createState() => new RandomWordsState();
}

class RandomWordsState extends State<RandomWords> {
  final _suggestions = <WordPair>[];
  final _bigFont = const TextStyle(fontSize: 18);
  final _saved = new Set<WordPair>();

  @override
  Widget build(BuildContext context) {
    //    WordPair wordPair = new WordPair.random();
    //    return new Text(wordPair.asCamelCase);
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(
          "this is a appbar",
          style: Theme.of(context).textTheme.title,
        ),
        actions: <Widget>[
          new IconButton(icon: new Icon(Icons.list), onPressed: pushSaved)
        ],
      ),
      body: buildSuggestions(),
    );
  }

  Widget buildSuggestions() {
    return new ListView.builder(
      padding: const EdgeInsets.all(16.0),
      // 对于每个建议的单词对都会调用一次itemBuilder，然后将单词对添加到ListTile行中
      // 在偶数行，该函数会为单词对添加一个ListTile row.
      // 在奇数行，该函数会添加一个分割线widget，来分隔相邻的词对。
      // 注意，在小屏幕上，分割线看起来可能比较吃力。
      itemBuilder: (context, i) {
        if (i.isOdd) {
          // 在每一列之前，添加一个1像素高的分隔线widget
          return new Divider();
        }
        // 语法 "i ~/ 2" 表示i除以2，但返回值是整形（向下取整），比如i为：1, 2, 3, 4, 5
        // 时，结果为0, 1, 1, 2, 2， 这可以计算出ListView中减去分隔线后的实际单词对数量
        int index = i ~/ 2;
        if (index >= _suggestions.length) {
          _suggestions.addAll(generateWordPairs().take(10));
        }
        return buildRow(_suggestions[index]);
      },
    );
  }

  Widget buildRow(WordPair wordPair) {
    final alreadySave = _saved.contains(wordPair);
    return new ListTile(
      title: new Text(
        wordPair.asPascalCase,
        style: _bigFont,
      ),
      trailing: new Icon(
        alreadySave ? Icons.favorite : Icons.favorite_border,
        //        color: alreadySave ? Colors.red, Colors.grey,
      ),
      onTap: () {
        //在Flutter的响应式风格的框架中，调用setState() 会为State对象触发build()方法，从而导致对UI的更新
        setState(() {
          print("setState");
          if (alreadySave) {
            _saved.remove(wordPair);
          } else {
            _saved.add(wordPair);
          }
        });
      },
      onLongPress: () {
        print("onLongPress");
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return new ContextWidget();
        }));
      },
    );
  }

  void pushSaved() {
    Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
      final titles = _saved.map(
        (pair) {
          return new ListTile(
            title: new Text(
              pair.asCamelCase,
              style: _bigFont,
            ),
          );
        },
      );
      final divided =
          ListTile.divideTiles(context: context, tiles: titles).toList();
      return new Scaffold(
        appBar: new AppBar(
          title: new Text("save suggestion"),
        ),
        body: new ListView(
          children: divided,
        ),
      );
    }));
  }

  @override
  void initState() {
    super.initState();
    print("initState");
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print("didChangeDependencies");
  }

  @override
  void didUpdateWidget(RandomWords oldWidget) {
    super.didUpdateWidget(oldWidget);
    print("didUpdateWidget");
  }

  @override
  void reassemble() {
    super.reassemble();
    print("reassemble");
  }

  @override
  void deactivate() {
    super.deactivate();
    print("deactivate");
  }

  @override
  void dispose() {
    super.dispose();
    print("dispose");
  }
}

class ContextWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "测试",
          textAlign: TextAlign.center,
          style: TextStyle(
            color: Colors.red,
            fontSize: 18,
            height: 1.2,
            background: new Paint()..color = Colors.yellowAccent,
          ),
        ),
      ),
      body: Container(
        child: Builder(builder: (context) {
          return Column();
        }),
      ),
    );
  }
}
